package com.yellow.feedbackservice.controller;

import com.yellow.feedbackservice.dao.FeedbackRepository;
import com.yellow.feedbackservice.entity.Feedback;
import com.yellow.feedbackservice.vo.Result;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/feedback")
@CrossOrigin("*")
public class FeedbackController {
    private final FeedbackRepository repository;

    public FeedbackController(FeedbackRepository repository) {
        this.repository = repository;
    }

    @PostMapping("/submit")
    public Result<Feedback> submitFeedback(@RequestBody Feedback feedback) {
        try {
            Feedback savedFeedback = repository.save(feedback);
            return Result.success(savedFeedback);
        } catch (Exception e) {
            return Result.fail("Failed to submit feedback: " + e.getMessage());
        }
    }

    @GetMapping("/getById/{id}")
    public Result<Feedback> getFeedback(@PathVariable String id) {
        return repository.findById(id)
                .map(Result::success)
                .orElse(Result.fail("Feedback not found with id: " + id));
    }

    @GetMapping("/listAll")
    public Result<Iterable<Feedback>> getAllFeedback() {
        try {
            Iterable<Feedback> feedbacks = repository.findAll();
            return Result.success(feedbacks);
        } catch (Exception e) {
            return Result.fail("Failed to retrieve feedbacks: " + e.getMessage());
        }
    }

    @DeleteMapping("/delById/{id}")
    public Result<Void> deleteFeedback(@PathVariable String id) {
        try {
            if (repository.existsById(id)) {
                repository.deleteById(id);
                return Result.success(null);
            } else {
                return Result.fail("Feedback not found with id: " + id);
            }
        } catch (Exception e) {
            return Result.fail("Failed to delete feedback: " + e.getMessage());
        }
    }
}